Msg("------------------------------\n")
Msg("MoneyMod 0.2a - SBRP Loading..\n")
include("moneymod_config.lua")
include("moneymod_pricelist.lua") // The new master pricelist :D
include("moneymod_proppriceoverride.lua") // Prop price override :)
Msg("MoneyMod 0.2a - SBRP Loaded...\n")
Msg("------------------------------\n")

if SERVER then
AddCSLuaFile("autorun/shared.lua");
end

///////////////////////////////////////////////////////////////////////////////////////////////////
// Console Command Shit
///////////////////////////////////////////////////////////////////////////////////////////////////
function TradeMoney(ply,cmd,arg)
MsgAll("PAY " .. arg[1] .. " " .. arg[2] .. " " .. ply:GetName())
ply:MoneyMod_PayThem(arg[1], arg[2])
end
concommand.Add("pay",TradeMoney)

function ListPlayers(ply)
for _,v in pairs ( player.GetAll() ) do
  ply:PrintMessage( HUD_PRINTTALK, v:Nick().." = "..v:EntIndex() )
end 
end
concommand.Add("listplayers",ListPlayers)

  /////////////////////////
 // Admin functionality //
/////////////////////////
// Get all ballances
function GetAllPlayerBallances(ply)
if !ply:IsAdmin() then return end
	ply:PrintMessage(HUD_PRINTTALK,"EntID SteamID Name Amount");
	for k, v in pairs(player.GetAll()) do
		if v != nil then
			ply:PrintMessage(HUD_PRINTTALK,v:EntIndex() .. " " .. v:GetName() .. " " .. v:MoneyMod_CurrentFunds())
		end
	end 	
end
concommand.Add("getallballances",GetAllPlayerBallances);

function IncreaseBallance(ply,cmd,args)
local targetid = args[1]
local amount = args[2]
if (CLIENT) or (!ply:IsAdmin())then return end // serverside only, sry peeps

local target = player.GetByID(targetid)

if (target == nil) then return end
if !(target.IsPlayer()) then return end

target:MoneyMod_GiveMoney(amount)

	for k, v in pairs(player.GetAll()) do
		if v != nil then
			v:PrintMessage(HUD_PRINTTALK,"(ADMIN)" .. ply:GetName() .. " gave " .. CUR .. amount .. " to " .. target:GetName())
		end
	end 

end
concommand.Add("increaseballance",IncreaseBallance)

function DecreaseBallance(ply,cmd,args)
local targetid = args[1]
local amount = args[2]
if (CLIENT) or (!ply:IsAdmin())then return end // serverside only, sry peeps

local target = player.GetByID(targetid)

if (target == nil) then return end
if !(target.IsPlayer()) then return end

target:MoneyMod_TakeMoney(amount)

	for k, v in pairs(player.GetAll()) do
		if v != nil then
			v:PrintMessage(HUD_PRINTTALK,"(ADMIN)" .. ply:GetName() .. " took " .. CUR .. amount .. " from " .. target:GetName())
		end
	end 

end
concommand.Add("decreaseballance",DecreaseBallance)

function MoneyMod_Help(ply)
ply:PrintMessage( HUD_PRINTTALK, "MoneyMod SBRP Help" )
ply:PrintMessage( HUD_PRINTTALK, "-= General User Commands =-" )
ply:PrintMessage( HUD_PRINTTALK, "pay <player entno> <amount>, Pay a player x amount, note the entno IS NOT the status number\n  the ent no can be obtained with listplayers" )
ply:PrintMessage( HUD_PRINTTALK, "listplayers, Goes with out saying, lists the player's entity index :P" )
ply:PrintMessage( HUD_PRINTTALK, "moneymod_help, Brings up this help information" )
ply:PrintMessage( HUD_PRINTTALK, "-= Admin Only Commands =-" )
ply:PrintMessage( HUD_PRINTTALK, "getallballances, Lists all the currently connected player's ballances" )
ply:PrintMessage( HUD_PRINTTALK, "increaseballance <entid> <amount>, Increases the players ballance by x (note all players are notified of this action)")
ply:PrintMessage( HUD_PRINTTALK, "decreaseballance <entid> <amount>, Decreases the players ballance by x (note all players are notified of this action)")
end
concommand.Add("moneymod_help",MoneyMod_Help)

///////////////////////////////////////////////////////////////////////////////////////////////////
// Events etc
///////////////////////////////////////////////////////////////////////////////////////////////////
/// Init
function FirstSpawn( ply )
	ply:MoneyMod_InitSpawn()
	ply:PrintMessage( HUD_PRINTTALK, "Welcome To Money Mod Spacebuild Role Play" ) 
end    
hook.Add( "PlayerInitialSpawn", "playerInitialSpawn", FirstSpawn ); 

function PayRoll()
for k, v in pairs(player.GetAll()) do
	if v != nil then
		v:MoneyMod_GiveMoney(payroll_amount)
		Msg( "Paid: " .. v:Nick() .. " $" .. payroll_amount ..  "\n")
		v:PrintMessage( HUD_PRINTTALK, "You received your paycheck of " .. CUR .. payroll_amount ) 
	end
end 
end 

function Audit()
local strTemp
local ent
local tempprice
local tempowner
local AuditStart = RealTime()
local AuditRun = 0
local EntityCount = 0
local ChargeTally = 0
local filterclass
Msg("Conducting Audit\n")
	for k, v in pairs( ents.GetAll() ) do
		// v = ent
		ent = v // STUPID FUCKING ERROR
		if ent != nil then
			filterclass = ent:GetClass()
			if ent:GetVar("paid",nil) == nil and ent:GetNetworkedEntity("OwnerObj", nil) != nil and !ent:IsWeapon() then
				if ent:GetNetworkedEntity("OwnerObj"):IsPlayer() then
					tempowner = ent:GetNetworkedEntity("OwnerObj")
					// we want the entity and its model (to allow for life support devices)
					strTemp = ent:GetClass() .. ","
					// Spam everyones! console with it so we can write the config file
					//MsgAll("\"" .. strTemp .. "\n")
					for _,v in pairs(class_pricelist) do
						if string.find(v,strTemp) != nil then
							tempprice = tonumber(string.Replace(v,strTemp,"")) // should leave us with le price
							if tempprice > tempowner:MoneyMod_CurrentFunds() then
								// Player can't afford it
								tempowner:PrintMessage( HUD_PRINTTALK, "Your prop " .. ent:GetClass() .. " was removed due to lack of funds" ) 
								ent:Remove()
							else
								// Player CAN afford it :D
								tempowner:MoneyMod_TakeMoney(tempprice)
								ChargeTally = ChargeTally + tempprice
								ent:SetVar("paid",1)
								tempowner:PrintMessage( HUD_PRINTTALK, "You where charged " .. CUR .. tempprice .. " for " .. ent:GetClass()) 
							end
						end
					end
				end
				EntityCount = EntityCount + 1
			end
		end
	end 
	for k, v in pairs( ents.GetAll() ) do
		// v = ent
		ent = v // STUPID FUCKING ERROR
		if ent != nil then
		if ent:GetVar("paid",nil) == nil and ent:GetNetworkedEntity("OwnerObj", nil) != nil then
				if ent:GetNetworkedEntity("OwnerObj"):IsPlayer() then
					tempowner = ent:GetNetworkedEntity("OwnerObj")
					// we want the entity and its model (to allow for life support devices)
					local mymodel
					if ent:GetModel() != nil then
						mymodel = ent:GetModel()
						strTemp = ent:GetClass() .. "," .. mymodel .. ","
						Msg("\"" .. strTemp .. "\n")
					else 
						mymodel = ""
						strTemp = ""
					end
					strTemp = ent:GetClass() .. "," .. mymodel .. ","
					// Spam everyones! console with it so we can write the config file
					
					for _,v in pairs(entity_pricelist)  do
						if string.find(v,strTemp) != nil and (ent:GetModel() != nil) then
							tempprice = tonumber(string.Replace(v,strTemp,"")) // should leave us with le price
							if tempprice > tempowner:MoneyMod_CurrentFunds() then
								// Player can't afford it
								tempowner:PrintMessage( HUD_PRINTTALK, "Your prop " .. ent:GetClass() .. " was removed due to lack of funds" ) 
								ent:Remove()
							else
								// Player CAN afford it :D
								tempowner:MoneyMod_TakeMoney(tempprice)
								ChargeTally = ChargeTally + tempprice
								ent:SetVar("paid",1)
								tempowner:PrintMessage( HUD_PRINTTALK, "You where charged " .. CUR .. tempprice .. " for " .. ent:GetClass()) 
							end
						end
					end
				end
			end 
		end
	end 
AuditRun = RealTime() - AuditStart
Msg("Audit Completed, It took, " .. AuditRun .. " seconds to process: " .. EntityCount .. " entities, and charge a total of " .. CUR .. ChargeTally .. "\n")
end

function MyTicker()
// Process Payrolls
PayRoll()
// Conduct audit
Audit()
end
timer.Create("MyTicker",60,0,MyTicker);

///////////////////////////////////////////////////////////////////////////////////////////////////
// FOUND THESE functions AT THE BOTTOM OF http://wiki.garrysmod.com/wiki/?title=Gamemode_Hooks   //
///////////////////////////////////////////////////////////////////////////////////////////////////

/// EXPENSE INDUCING EVENTS ;)

local function ReturnLargest(ent)
	local mina = ent:OBBMins()
	local maxa = ent:OBBMaxs()
	local surface_x = (maxa.x-mina.x)
	local surface_y = (maxa.y-mina.y)
	local surface_z = (maxa.z-mina.z)
	local surf_x,surf_y,surf_z
	surf_x = surface_x * surface_z
	surf_y = surface_y * surface_z
	surf_z = surface_x * surface_y
	local currentlgest = 0
	
	if(surf_x >= currentlgest) then
		currentlgest = surf_x
	end
	
	if(surf_y >= currentlgest) then
		currentlgest = surf_y
	end
	
	if(surf_z >= currentlgest) then
		currrentlgest = surf_z
	end
	
	return currentlgest
end

local function dePlayerSpawnedProp( ply, mdl, ent )
	local min, max = ent:OBBMins(), ent:OBBMaxs()
	local vol = math.abs(max.x-min.x) * math.abs(max.y-min.y) * math.abs(max.z-min.z)
	vol = math.Round(vol/(16^3))
	local MaxSurface = ReturnLargest(ent)/(16^2)
	
	local approx_rate2 = (payroll_amount * 20) / 1876 // 20 minutes to obtains a steakknife @ 1876 square feet
	local approx_cost2 = math.Round(MaxSurface * approx_rate2)
	local tempprice
	//ply:PrintMessage(HUD_PRINTTALK,"Largest Surface area is: " .. MaxSurface .. "\n   And approximate cost is: " .. approx_cost2 );
	local tempstr = mdl .. ","
	for _,v in pairs(moneymod_proppriceoverride)  do
		if string.find(v,tempstr) != nil then
			tempprice = tonumber(string.Replace(v,tempstr,"")) // should leave us with le price
			if tempprice > ply:MoneyMod_CurrentFunds() then
				// Player can't afford it
				ply:PrintMessage( HUD_PRINTTALK, "Your prop " .. mdl .. " was removed due to lack of funds" ) 
				ent:Remove()
			else
				// Player CAN afford it :D
				ply:MoneyMod_TakeMoney(tempprice)
				ply:PrintMessage( HUD_PRINTTALK, "You where charged " .. CUR .. tempprice .. " for " .. mdl) 
			end
			return
		end
	end
	
	
	// Costing
	// steakknife should take 20 mintues to obtain, has a volume of 129833.81768962 CF
	// cost per cubic foot = (Pay rate * Time to get) / Vol
	local approx_rate = (payroll_amount * 20) / 129834
	local approx_cost = math.Round(vol * approx_rate)
	
	if approx_cost == 0 then
		approx_cost = 50 // band-aid fix to solve a minor issue of large props with small volumes :|
	end

	if(ply:MoneyMod_CurrentFunds() < approx_cost) then // Ship encumbership will be here
		ent:Remove();
		ply:PrintMessage( HUD_PRINTTALK, "You need more money to build that!" ); 
		return
	end
	
MsgAll("Player: " .. ply:GetName() .. " spawned " .. mdl .. " with a volume of " .. vol .. " cubic feet, and it costed: " .. CUR .. approx_cost .. "\n")
ply:PrintMessage( HUD_PRINTTALK, "It costed you  " .. CUR .. approx_cost .. "\n" ); 
ply:MoneyMod_TakeMoney(approx_cost)
end
hook.Add( "PlayerSpawnedProp", "dePlayerSpawnedProp", dePlayerSpawnedProp ) 

function dePlayerSpawnedVehicle(ply,ent)
local entity_name = ent:GetClass()
MsgAll("Player: " .. ply:GetName() .. " spawned " .. entity_name .. "\n")
	if(ply:MoneyMod_CurrentFunds() < vehicle_price) then // Ship encumbership will be here
		ply:PrintMessage( HUD_PRINTTALK, "You need more money to buy that!" ); 
		ent:Remove()
		return false
	end
	ply:MoneyMod_TakeMoney(vehicle_price)
	ply:PrintMessage( HUD_PRINTTALK, "It costed you " .. CUR .. vehicle_price .. "\n" ); 
end
hook.Add( "PlayerSpawnedVehicle", "dePlayerSpawnedVehicle", dePlayerSpawnedVehicle );

if(MoneyMod_SetTags == true) then // Add teh tags if told to
game.ConsoleCommand( "sv_tags MoneyMod\n" )
end 